package com.UdpRecieve.Netty.codec;



import com.UdpRecieve.Netty.protocol.FilePacket;
import com.UdpRecieve.Netty.protocol.Packet;
import com.UdpRecieve.Netty.protocol.request.LoginPacket;
import com.UdpRecieve.Netty.protocol.response.LoginResponsePacket;
import com.UdpRecieve.Netty.protocol.serilizer.Serilizer;
import io.netty.buffer.ByteBuf;

import java.util.HashMap;
import java.util.Map;

import static com.UdpRecieve.Netty.protocol.command.Command.*;


public class Codec {

	public static final int TYPE = 0x12345678;//16进制

	private final Map<Byte, Class<? extends Packet>> packetTypeMap;

	public static Codec INSTANCE = new Codec();

	private Codec() {
		packetTypeMap = new HashMap<>();
		packetTypeMap.put(FILE_PACKET, FilePacket.class);//1
		packetTypeMap.put(LOGIN_PACKET_REQUEST, LoginPacket.class);//2
		packetTypeMap.put(LOGIN_PACKET_RESPONSE, LoginResponsePacket.class);//3
	}

	public void encode(ByteBuf byteBuf, Packet packet) {
		/*创建JSONSerilizer类*/
		byte[] bytes = Serilizer.DEFAULT.serilize(packet);
		byteBuf.writeInt(TYPE);
		byteBuf.writeByte(packet.getCommand());
		byteBuf.writeInt(bytes.length);
		byteBuf.writeBytes(bytes);
		// return byteBuf;
	}

	public Packet decode(ByteBuf byteBuf) {
		int i = byteBuf.readInt();//type
		Byte command = byteBuf.readByte();//内容(1\2\3)
		int len = byteBuf.readInt();//内容长度
		//System.out.println(len);
		byte[] bytes = new byte[len];
		byteBuf.readBytes(bytes);
		Class clazz = packetTypeMap.get(command);
		if (clazz == null) {
			throw new NullPointerException("解析失败，没有该类型的数据包");
		}
		/*new JSONSerilizer();*/
		return (Packet) Serilizer.DEFAULT.deSerilize(bytes, clazz);

	}



}
